
package com.service.impl;


import java.util.Calendar;
import java.util.Date;

import com.constant.AuthConstant;
import com.dao.WeixiuyuanDao;
import com.domain.entity.WeixiuyuanEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dao.TokenDao;
import com.domain.entity.TokenEntity;
import com.service.TokenService;


@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private WeixiuyuanDao weixiuyuanDao;


    @Override
    public void insertToken(Long id, String username, String tableName, String role, String token) {

        TokenEntity tokenEntity = this.selectOne(new EntityWrapper<TokenEntity>().eq("userid", id).eq("role", role));

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR_OF_DAY, 24);

        if (AuthConstant.ADMIN_ROLE.equals(role)) {
            //往token表中添加管理员的信息
            if (tokenEntity != null) {
                //如果数据库中存在数据
                tokenEntity.setToken(token);
                tokenEntity.setExpiratedtime(cal.getTime());
                tokenEntity.setLogintime(new Date());
                tokenDao.updateById(tokenEntity);
            } else {
                //如果数据库中不存在数据
                tokenDao.insert(new TokenEntity(id, username, tableName, role, token, cal.getTime(), new Date()));
            }
        } else {
            //往token表中添加维修员的信息
            if (tokenEntity != null) {
                //如果数据库中存在数据
                tokenEntity.setToken(token);
                tokenEntity.setExpiratedtime(cal.getTime());
                tokenEntity.setLogintime(new Date());
                tokenDao.updateById(tokenEntity);
            } else {
                //如果数据库中不存在数据
                WeixiuyuanEntity maintenanceMan = weixiuyuanDao.selectById(id);

                tokenDao.insert(
                        new TokenEntity(id, username, tableName, role, token, cal.getTime(),
                                new Date(), maintenanceMan.getAddress(), maintenanceMan.getGender(),
                                maintenanceMan.getIdentityCard(), maintenanceMan.getPhoneNumber(),
                                maintenanceMan.getJobNumber()));
            }

        }


    }

}
